package com.flyiu.data.consistency.repository;

import java.util.List;

import javax.persistence.LockModeType;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Lock;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import com.flyiu.data.consistency.model.DistributedTransactionInstance;
import com.flyiu.data.consistency.model.DistributedTransactionState;

public interface DistributedTransactionInstanceRepository
		extends JpaRepository<DistributedTransactionInstance, Integer>,
		JpaSpecificationExecutor<DistributedTransactionInstance> {
	
	@Transactional(timeout = 2)
	@Lock(value = LockModeType.PESSIMISTIC_WRITE)
	@Query("select i from DistributedTransactionInstance i where id = :id and transactionState =:state ")
	public DistributedTransactionInstance lockInstance(@Param(value = "state") DistributedTransactionState state,
			@Param(value = "id") Long id);
	
	@Transactional()
	@Modifying
	@Query("update DistributedTransactionInstance set transactionState =:state  where id in (:ids)")
	public void changeStatus(@Param(value = "state") DistributedTransactionState state,@Param(value = "ids") List<Long> ids);
}
